package com.ting.encrypt.utils;

import com.ting.common.enums.ResultEnum;
import com.ting.common.exception.TingBaseException;
import com.ting.encrypt.annotation.EncryptField;
import com.ting.encrypt.encrypt.BaseEncrypt;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * @author: guohaibing
 * @date: 2022/10/8 11:15
 * @description: TODO
 */
@Slf4j
@Component
public class EncryptUtil {
  
  @Autowired
  ApplicationContext applicationContext;

  /**
   * 给字段加密
   *
   * @param field
   * @param value
   * @return
   * @throws Exception
   */
  public Object handlerFieldEncrypt(Field field, Object value) throws Exception {
    // 判断这个属性上是否有加密注解
    EncryptField encryptField = field.getAnnotation(EncryptField.class);

    return getEncryptValue(value, encryptField);
  }

  public Object getEncryptValue(Object value, EncryptField encryptField) {
    if (encryptField == null || value == null || !(value instanceof String)) return value;

    Class<? extends BaseEncrypt> encryptClass = encryptField.encryptType();
    Object newValue = value;
    try {
      BaseEncrypt baseEncrypt = applicationContext.getBean(encryptClass);
      if(baseEncrypt == null) {
        baseEncrypt = encryptClass.newInstance();
      }

      // 对json中需要加密字段的处理
//      if (encryptField.isJsonField()) {
//        String[] encryptKeyword = encryptField.jsonFieldNames();
//        newValue =
//            JsonUtil.operatorKeyword(value, baseEncrypt, encryptKeyword, OperateType.ENCRYPT);
//      } else {
        newValue = baseEncrypt.encrypt((String) value);
//      }
    } catch (Exception e) {
      log.error("数据加密失败", e);
      throw new TingBaseException(ResultEnum.ENCRYPT_ERROR);
    }

    return newValue;
  }
  
  public Object getDecryptValue(Object value, EncryptField encryptField) {
    if (encryptField == null || value == null || !(value instanceof String)) return value;
    
    Class<? extends BaseEncrypt> encryptClass = encryptField.encryptType();
    Object newValue = value;
    try {
      BaseEncrypt baseEncrypt = applicationContext.getBean(encryptClass);
      if(baseEncrypt == null) {
        baseEncrypt = encryptClass.newInstance();
      }
      
      // 对json中需要加密字段的处理
//      if (encryptField.isJsonField()) {
//        String[] encryptKeyword = encryptField.jsonFieldNames();
//        newValue =
//                JsonUtil.operatorKeyword(value, baseEncrypt, encryptKeyword, OperateType.DECRYPT);
//      } else {
        newValue = baseEncrypt.decrypt((String) value);
//      }
    } catch (Exception e) {
      log.error("数据解密失败", e);
      throw new TingBaseException(ResultEnum.DECRYPT_ERROR);
    }
    
    return newValue;
  }
}
